package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-04-23
 * Time: 9:53
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {  //构造方法
        socket = new DatagramSocket();
        this.serverIp = serverIp;  //IP
        this.serverPort = serverPort;   //端口号
    }

    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.println("请输入要发送的请求: ");
            //1. 从控制台读取用户输入
            String request = sc.next();

            //2. 构造请求并发送
            //构建一个要发送给服务器的数据包  不光有 数据 还有 "目标"
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);  //InetAddress对象,把字符串格式的IP地址转成Java能识别的对象
            socket.send(requestPacket);

            //3. 读取响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096); //先创建一个空的数据报
            socket.receive(responsePacket);  //接收数据报写入空的数据报里面(接收等待期间会阻塞等待)

            //4. 显示响应到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());  //本身是字节的就可以直接getlength
            System.out.println("返回的内容是: ");
            System.out.println(response);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
